#!/bin/bash
hosts=$(cat host)
str='#'
ch=('|' '\' '-' '/')
index=0
i=0
flag=false
while getopts ":s:t:" opt
do
    case $opt in
        s)
        source=$OPTARG
        echo "您输入的原始文件:$source"
        ;;
        t)
        target=$OPTARG
        echo "您输入的目标位置:$target"
        ;;
        ?)
        echo "未知参数,你可以这样使用 : sh process.sh -t /opt"
        exit 1;;
    esac
done
echo ""
ctrl_c_handler() {
    for single_host in ${hosts[@]}
    do
      echo ""
    done
    exit 1
}

# 设置 trap，捕获 SIGINT 信号并执行 ctrl_c_handler 函数
trap 'ctrl_c_handler' SIGINT
#printf "\e[?251"
array_hosts=($hosts)
declare -A host_map
for single_host in ${hosts[@]}
do
	host_map["$single_host"]=1
done
while [[ "$flag" == "false" ]]
do
	if [[ "$i" -gt "0" ]]
	then
		printf "\033[${#array_hosts[@]}A\r"
	fi
	i=0
	for single_host in ${hosts[@]}
	do
		if [[ ${host_map["$single_host"]} -eq 100 ]]
		then
			str=$(printf "%0.s-" $(seq 1 25))
			printf "[%-25s][%.2f%%][%c][%s]\n"  $str 100 ${ch[1]} ${single_host}
			continue
		fi
		current_size=$(PYTHONUNBUFFERED=1 sshpass -f password pssh -H ${single_host} -O "StrictHostKeyChecking=no" -A -l yapai -i "ls -al ${target} | grep ${source}" | sed -n '4p' | awk '{print $5}')
    if [[ -z ${current_size} ]]
    then
      current_size=0
    fi
		source_size=$(ls -al ${source} | awk '{print $5}')
		result=$(echo "scale=2;($current_size*100/$source_size)" | bc -l)
		integer_part=$(echo "$result/1" | bc )
		radio_part=$(echo "$integer_part/4" | bc )
		index=$(echo "$integer_part%4" | bc )
		str=$(printf "%0.s-" $(seq 1 $radio_part))
		if [[ "$integer_part" == "100" ]]
		then
      lsof_pid=$(PYTHONUNBUFFERED=1 sshpass -f password pssh -H ${single_host} -O "StrictHostKeyChecking=no" -A -l yapai -i "lsof -t ${target}/${source}")
      if [[ ! -z $lsof_pid ]]
      then
        err="twice"
      fi
			host_map[$single_host]=100
			str=$(printf "%0.s-" $(seq 1 25))
			printf "[%-25s][%.2f%%][%c][%s]\n"  $str 100 ${ch[1]} ${single_host}${err}
			continue
		else
			let i++
			random_index=$((RANDOM%4))
			printf "[%-25s][%.2f%%][%c][%s]\n"  $str $result ${ch[$random_index]} ${single_host}
		fi

	done
	if [[ "$i" == "0" ]]
	then
		flag=true
	fi
done
#printf "\e[?25h"
for single_host in ${hosts[@]}
do
	echo "${single_host} server successful"
done
